<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>患者详情</h3>
          <div class="header-actions">
            <el-button 
              type="primary" 
              @click="handleEdit" 
              v-permission="'patient:update'"
            >
              编辑
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-loading="loading">
        <!-- 基本信息 -->
        <el-descriptions 
          title="基本信息" 
          :column="4" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="患者ID">
            {{ patient.patientId || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ patient.name || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            {{ patient.gender || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="出生日期">
            {{ formatDate(patient.birthDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="年龄">
            {{ calculateAge(patient.birthDate) }}岁
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            {{ patient.idNumber || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="登记日期">
            {{ formatDateTime(patient.registrationDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="patient.activeStatus ? 'success' : 'danger'">
              {{ patient.activeStatus ? '有效' : '无效' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 联系信息 -->
        <el-descriptions 
          title="联系信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="手机号">
            {{ patient.contactInfo?.phone || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="紧急联系人">
            {{ patient.contactInfo?.emergencyContact || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="家庭住址">
            {{ patient.contactInfo?.address || '--' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 医疗信息 -->
        <el-descriptions 
          title="医疗信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="血型">
            {{ patient.medicalInfo?.bloodType || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="过敏史" :span="2">
            <div v-if="patient.medicalInfo?.allergies && patient.medicalInfo.allergies.length > 0">
              <el-tag 
                v-for="allergy in patient.medicalInfo.allergies" 
                :key="allergy"
                class="tag-item"
                type="danger"
              >
                {{ allergy }}
              </el-tag>
            </div>
            <span v-else>无</span>
          </el-descriptions-item>
          <el-descriptions-item label="慢性病史" :span="3">
            <div v-if="patient.medicalInfo?.chronicDiseases && patient.medicalInfo.chronicDiseases.length > 0">
              <el-tag 
                v-for="disease in patient.medicalInfo.chronicDiseases" 
                :key="disease"
                class="tag-item"
                type="warning"
              >
                {{ disease }}
              </el-tag>
            </div>
            <span v-else>无</span>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 保险信息 -->
        <el-descriptions 
          title="保险信息" 
          :column="3" 
          border
          class="margin-bottom"
        >
          <el-descriptions-item label="保险公司">
            {{ patient.insuranceInfo?.provider || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="保单号">
            {{ patient.insuranceInfo?.policyNumber || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="到期日期">
            {{ formatDate(patient.insuranceInfo?.expiryDate) }}
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 患者标签 -->
        <el-card shadow="never" class="margin-bottom">
          <template #header>
            <div class="card-sub-header">
              <span>患者标签</span>
            </div>
          </template>
          <div v-if="patient.tags && patient.tags.length > 0">
            <el-tag 
              v-for="tag in patient.tags" 
              :key="tag"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
          </div>
          <span v-else>无</span>
        </el-card>
        
        <!-- 医疗记录 -->
        <el-card shadow="never">
          <template #header>
            <div class="card-sub-header">
              <span>医疗记录</span>
              <el-button 
                type="primary" 
                size="small"
                v-permission="'medical_record:read'"
                @click="viewMedicalRecords"
              >
                查看全部
              </el-button>
            </div>
          </template>
          
          <el-table
            v-loading="recordsLoading"
            :data="medicalRecords"
            border
            style="width: 100%"
          >
            <el-table-column prop="recordId" label="记录ID" width="180" />
            <el-table-column prop="doctorName" label="医生" width="120" />
            <el-table-column prop="visitType" label="就诊类型" width="100" />
            <el-table-column prop="diagnosis" label="诊断" min-width="200" />
            <el-table-column label="就诊日期" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.visitDate) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="120">
              <template #default="scope">
                <el-button 
                  link 
                  type="primary" 
                  size="small"
                  @click="viewMedicalRecord(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div v-if="medicalRecords.length === 0 && !recordsLoading" class="empty-data">
            暂无医疗记录
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { patientAPI, medicalRecordAPI } from '@/utils/api'
import { formatDate, formatDateTime, calculateAge } from '@/utils/date'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const recordsLoading = ref(false)
const patient = reactive({})
const medicalRecords = ref([])

// 获取患者详情
const getPatientDetails = async (id) => {
  loading.value = true
  try {
    const res = await patientAPI.getPatient(id)
    // 清空之前的患者数据
    Object.keys(patient).forEach(key => {
      delete patient[key]
    })
    // 添加新的患者数据
    Object.assign(patient, res.data)
  } catch (error) {
    console.error('获取患者详情失败', error)
    ElMessage.error('获取患者详情失败')
  } finally {
    loading.value = false
  }
}

// 获取患者的医疗记录
const getPatientMedicalRecords = async (id) => {
  recordsLoading.value = true
  try {
    const res = await patientAPI.getPatientMedicalRecords(id, { limit: 5 })
    medicalRecords.value = res.data.medicalRecords || []
    console.log('获取到医疗记录数据:', medicalRecords.value.length, '条记录')
  } catch (error) {
    console.error('获取医疗记录失败', error)
    ElMessage.error('获取医疗记录失败')
  } finally {
    recordsLoading.value = false
  }
}

// 监听路由参数变化
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log('患者ID变更:', oldId, '->', newId)
    getPatientDetails(newId)
    getPatientMedicalRecords(newId)
  }
}, { immediate: true })

// 查看医疗记录详情
const viewMedicalRecord = (record) => {
  router.push(`/medical-records/detail/${record.recordId}`)
}

// 查看全部医疗记录
const viewMedicalRecords = () => {
  router.push({
    path: '/medical-records/list',
    query: { patientId: patient.patientId }
  })
}

// 编辑患者
const handleEdit = () => {
  router.push(`/patients/edit/${patient.patientId}`)
}

// 返回上一页
const goBack = () => {
  router.push('/patients/list')
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-sub-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.margin-bottom {
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 5px;
}

.empty-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}
</style> 